<template>
    <div ref="chartRef" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
    props: {
        data: {
            type: Array,
            required: true
        },
        timeType: {
            type: String,
            required: true,
            validator: value => ['hour', 'day', 'month', 'year'].includes(value)
        },
        width: {
            type: String,
            default: '100%'
        },
        height: {
            type: String,
            default: '500px'
        },
        fields: {
            type: Array,
            default: () => ['temperature', 'pressure', 'humidity', 'water', 'rain']
        }
    },
    data() {
        return {
            chartInstance: null
        };
    },
    watch: {
        data: {
            deep: true,
            handler() {
                this.initChart();
            }
        }
    },
    mounted() {
        this.initChart();
    },
    methods: {
        initChart() {
            if (this.chartInstance) {
                this.chartInstance.dispose();
            }

            this.chartInstance = echarts.init(this.$refs.chartRef);

            const timeFormatMap = {
                hour: 'hh时',
                day: 'dd日',
                month: 'MM月',
                year: 'yyyy年'
            };

            const tooltipFormatMap = {
                hour: 'yyyy年MM月dd日hh时',
                day: 'yyyy年MM月dd日',
                month: 'yyyy年MM月',
                year: 'yyyy年'
            };

            const timeFormat = timeFormatMap[this.timeType];
            const tooltipFormat = tooltipFormatMap[this.timeType];

            const times = this.data.map(item => {
                const date = new Date(item.time);
                return echarts.format.formatTime(timeFormat, date);
            });

            const fieldMap = {
                temperature: '温度',
                pressure: '气压',
                humidity: '湿度',
                water: '水位',
                rain: '降雨量'
            };

            const unitMap = {
                '温度': '°C',
                '气压': 'hPa',
                '湿度': '%',
                '水位': 'm',
                '降雨量': 'mm'
            };

            const series = this.fields.map(field => {
                const data = this.data.map(item => item[field]);
                return {
                    name: fieldMap[field],
                    type: field === 'rain' ? 'bar' : 'line',
                    data: data,
                    yAxisIndex: 0 // 所有系列都使用同一个 Y 轴
                };
            });

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        const time = params[0].dataIndex;
                        const date = new Date(this.data[time].time);
                        const timeStr = echarts.format.formatTime(tooltipFormat, date);
                        let tooltip = `<div>${timeStr}</div>`;
                        params.forEach(param => {
                            const field = param.seriesName;
                            const unit = unitMap[field];
                            tooltip += `<div>${param.seriesName}: ${param.value.toFixed(2)} ${unit}</div>`;
                        });
                        return tooltip;
                    }.bind(this)
                },
                toolbox: {
                    feature: {
                        saveAsImage: {
                            type: 'png', // 图片格式，支持：'png', 'jpeg'
                            name: 'chart', // 下载的文件名
                            title: '下载图片' // 鼠标悬停时显示的文本
                        }
                    }
                },
                legend: {
                    data: this.fields.map(field => fieldMap[field])
                },
                xAxis: {
                    type: 'category',
                    data: times
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '',

                    }
                ],
                series: series
            };

            this.chartInstance.setOption(option);
        }
    },
    beforeDestroy() {
        if (this.chartInstance) {
            this.chartInstance.dispose();
        }
    }
};
</script>